package org.example.controller;

import org.example.entity.SystemConfig;
import org.example.service.SystemConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.Optional;

/**
 * 系统配置控制器
 */
@RestController
@RequestMapping("/system-configs")
@CrossOrigin(origins = "*")
public class SystemConfigController {
    
    @Autowired
    private SystemConfigService systemConfigService;
    
    /**
     * 创建系统配置
     */
    @PostMapping
    public ResponseEntity<?> createConfig(@Valid @RequestBody SystemConfig config) {
        try {
            SystemConfig createdConfig = systemConfigService.createConfig(config);
            return ResponseEntity.status(HttpStatus.CREATED).body(createdConfig);
        } catch (RuntimeException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }
    
    /**
     * 根据ID获取配置
     */
    @GetMapping("/{id}")
    public ResponseEntity<?> getConfigById(@PathVariable Long id) {
        Optional<SystemConfig> config = systemConfigService.findById(id);
        if (config.isPresent()) {
            return ResponseEntity.ok(config.get());
        } else {
            return ResponseEntity.notFound().build();
        }
    }
    
    /**
     * 根据配置键获取配置
     */
    @GetMapping("/key/{configKey}")
    public ResponseEntity<?> getConfigByKey(@PathVariable String configKey) {
        Optional<SystemConfig> config = systemConfigService.findByConfigKey(configKey);
        if (config.isPresent()) {
            return ResponseEntity.ok(config.get());
        } else {
            return ResponseEntity.notFound().build();
        }
    }
    
    /**
     * 根据配置键获取配置值
     */
    @GetMapping("/value/{configKey}")
    public ResponseEntity<String> getConfigValue(@PathVariable String configKey) {
        String value = systemConfigService.getConfigValue(configKey);
        if (value != null) {
            return ResponseEntity.ok(value);
        } else {
            return ResponseEntity.notFound().build();
        }
    }
    
    /**
     * 根据配置键获取配置值（带默认值）
     */
    @GetMapping("/value/{configKey}/default")
    public ResponseEntity<String> getConfigValueWithDefault(@PathVariable String configKey, @RequestParam String defaultValue) {
        String value = systemConfigService.getConfigValue(configKey, defaultValue);
        return ResponseEntity.ok(value);
    }
    
    /**
     * 获取所有配置
     */
    @GetMapping
    public ResponseEntity<List<SystemConfig>> getAllConfigs() {
        List<SystemConfig> configs = systemConfigService.findAllConfigs();
        return ResponseEntity.ok(configs);
    }
    
    /**
     * 根据配置键搜索
     */
    @GetMapping("/search/key")
    public ResponseEntity<List<SystemConfig>> searchConfigsByKey(@RequestParam String key) {
        List<SystemConfig> configs = systemConfigService.searchConfigsByKey(key);
        return ResponseEntity.ok(configs);
    }
    
    /**
     * 根据描述搜索配置
     */
    @GetMapping("/search/description")
    public ResponseEntity<List<SystemConfig>> searchConfigsByDescription(@RequestParam String description) {
        List<SystemConfig> configs = systemConfigService.searchConfigsByDescription(description);
        return ResponseEntity.ok(configs);
    }
    
    /**
     * 更新配置
     */
    @PutMapping("/{id}")
    public ResponseEntity<?> updateConfig(@PathVariable Long id, @Valid @RequestBody SystemConfig config) {
        try {
            config.setId(id);
            SystemConfig updatedConfig = systemConfigService.updateConfig(config);
            return ResponseEntity.ok(updatedConfig);
        } catch (RuntimeException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }
    
    /**
     * 根据配置键更新配置值
     */
    @PutMapping("/key/{configKey}/value")
    public ResponseEntity<?> updateConfigByKey(@PathVariable String configKey, @RequestBody ConfigValueRequest request) {
        try {
            SystemConfig config = systemConfigService.updateConfigByKey(configKey, request.getValue());
            return ResponseEntity.ok(config);
        } catch (RuntimeException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }
    
    /**
     * 删除配置
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<?> deleteConfig(@PathVariable Long id) {
        try {
            systemConfigService.deleteConfig(id);
            return ResponseEntity.ok("配置删除成功");
        } catch (RuntimeException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }
    
    /**
     * 根据配置键删除配置
     */
    @DeleteMapping("/key/{configKey}")
    public ResponseEntity<?> deleteConfigByKey(@PathVariable String configKey) {
        try {
            systemConfigService.deleteConfigByKey(configKey);
            return ResponseEntity.ok("配置删除成功");
        } catch (RuntimeException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }
    
    // 内部类用于请求体
    public static class ConfigValueRequest {
        private String value;
        
        public String getValue() { return value; }
        public void setValue(String value) { this.value = value; }
    }
}
